﻿using AuthCenter.API.Application.Command.RoleMenu;
using AuthCenter.API.DTOs;
using AuthCenter.Domain.Menu;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MediatR;
using System.Security.Cryptography;

namespace AuthCenter.API.Application.Handler.RoleMenu
{
    public class FindRoleMenuHandler : IRequestHandler<FindRoleMenuCommand, APIResult<List<RoleMenuDTO>>>
    {
        private readonly IBaseRepository<RoleMenuModel> rolemenuRepo;
        private readonly IBaseRepository<MenuModel> menuRepo;
        private readonly IMapper mapper;

        public FindRoleMenuHandler(IBaseRepository<RoleMenuModel> rolemenuRepo,
                                   IBaseRepository<MenuModel> menuRepo,
                                   IMapper mapper)
        {
            this.rolemenuRepo = rolemenuRepo;
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<List<RoleMenuDTO>>> Handle(FindRoleMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<RoleMenuDTO>> result = new APIResult<List<RoleMenuDTO>>();
            var res = rolemenuRepo.GetAll().Where(x => x.RoleId == request.RoleId).ToList();
            if (res == null)
            {
                result.Message = "找不到对应的角色编号";
                result.Code = APIEnum.Error;
                return Task.FromResult(result);
            }

            var model = mapper.Map<List<RoleMenuDTO>>(res);
            foreach (var item in model)
            {
                var menu = menuRepo.GetAll().FirstOrDefault(x => x.Id == item.MenuId);
                if (menu != null)
                {
                    item.MenuId = menuRepo.GetAll().FirstOrDefault(x => x.Id == item.MenuId).Id;
                    item.MenuName = menuRepo.GetAll().FirstOrDefault(x => x.Id == item.MenuId).MenuName;
                }
                else
                {
                    continue;
                }
            }
            result.Message = "查询成功";
            result.Data = model;
            result.Code = APIEnum.Ok;
            return Task.FromResult(result); 
        }
    }
}
